package com.usc.entme;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ListItemArrayAdapterMovies extends ArrayAdapter<MoviesObject>{
	int resource;
	private String TAG = "MoviesMessage";
	LayoutInflater vi;
	private List<MoviesObject> items;
	private Bitmap bmImg;

	public ListItemArrayAdapterMovies(Context context, int _resource, List<MoviesObject> listitems) 
	{
		super(context, _resource, listitems);
		Log.e( TAG ,"listItemArrayAdapter");
		vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		resource = _resource;
		this.items = listitems;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		Log.d(TAG, "listItemArrayAdapter.getView");
		LinearLayout newView;

		MoviesObject item = getItem(position);
		
		if (convertView == null) {
			newView = new LinearLayout(getContext());
			vi.inflate(R.layout.movieitem, newView);
		} else {
			newView = (LinearLayout)convertView;
		}
		
		TextView textViewTitle = (TextView)newView.findViewById(R.id.moviestitle);
		Log.d(TAG, item.title);
		textViewTitle.setText(item.title);
		
		TextView textViewDetail = (TextView)newView.findViewById(R.id.moviesdetail);
		Log.d(TAG, item.title);
		textViewDetail.setText(item.detail);
		
		ImageView imgView = (ImageView)newView.findViewById(R.id.moviesimage);
		//Log.d(TAG, item.imgUrl.toString());
		HttpURLConnection conn = null;
		try {
			URL imgUrl = new URL(item.imageUrl);
			Log.d(TAG,"Establishing Connection...");
			conn = (HttpURLConnection)imgUrl.openConnection();
			Log.d(TAG,"Conncetion Established");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 conn.setDoInput(true);
		 try {
			conn.connect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 int length = conn.getContentLength();
		 int[] bitmapData =new int[length];
		 byte[] bitmapData2 =new byte[length];
		 InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		 bmImg = BitmapFactory.decodeStream(is);
		 imgView.setImageBitmap(bmImg);


		 return newView;	 
	}

}